# -*- coding: utf-8 -*-
# @File      :connent_mysql
# @Author    :liaogan
# @Datetime  :2023/2/21 10:20

import pymysql

class  Fun_Database():

    def __init__(self,host='127.0.0.1',port=3306,database='mytest',user='root',password='123456',charset='utf8'):
        #创建连接
        self.conn=pymysql.connect(host=host,port=port,database=database,user=user,password=password,charset=charset)
        #获取游标
        self.cursor=self.conn.cursor()

    # def __init__(self,host='127.0.0.1',port=3306,database='mytest',user='root',password='123456',charset='utf8'):
    #     self.host=host
    #     self.port=port
    #     self.database=database
    #     self.user=user
    #     self.password=password
    #     self.charset=charset
    #     self.db=pymysql.connect(host=self.host,port=self.port,database=self.database,user=self.user,password=self.password)
    #     #获取游标
    #     self.cursor=self.db.cursor()

    #查询方法
    def select(self,sql,many=True):

        """

        :param sql:
        :param many:
        :return:
        """
        self.cursor.execute(sql)
        if many:
            #查询多条数据
            result=self.cursor.fetchall()
        else:
            # 查询1条数据
            result=self.cursor.fetchone()
        return result

    #增 删 改公共方法
    def do(self,sql):
        """

        :param sql:
        :return:
        """
        try:
            self.cursor.execute(sql)
        except Exception as error1:
            self.conn.rollback()

            print(f'mysqldb error1{ error1}')
            raise error1
        self.conn.commit()

    #增
    def insert(self,sql):

        self.do(sql)
    #删
    def delete(self,sql):
        self.do(sql)
    #改
    def update(self,sql):
        self.do(sql)

    #关闭游标和连接
    def exit(self):
        self.cursor.close()
        self.conn.close()


if __name__ == '__main__':
    db=Fun_Database()
    sql1='select * from b'
    # res=db.select(sql,many=True)
    # print(res)

    # sql = 'insert into b VALUES(1008,"english",131)'
    # res=db.insert(sql)
    # print(res)
    #
    # sql='delete from b where bno ="1006"'
    # res1=db.delete(sql)
    # print(res1)

    res2=db.select(sql1,many=False)
    print(res2)
    # db.exit()




